// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const voiceCollection = db.collection('voice')
const likeCollection = db.collection('liker_liked')
const _ = db.command
 let likedOpenId = ''
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const id = event.id || ''
  const state = event.state || ''
  let likeList = []
  if (id == '') return
  if (state == '') return

  if (state == 'like'){
    await voiceCollection.doc(id).get().then(res => {
      likedOpenId = res.data._openid
    })
    await likeCollection.add({
      data: {
        likerOpenId: wxContext.OPENID,
        likedVoiceId: id,
        likedOpenId,
        likeDate: new Date().getTime()
      }
    })
    await voiceCollection.doc(id).update({
      data: {
        // like: _.push(
        //   {
        //     likerOpenId: wxContext.OPENID,
        //     likeDate: new Date().getTime()
        //   }
        // ),
        likeCount: _.inc(1)
      }
    })
  }else{
    // await voiceCollection.doc(id).get().then(count => {
    //   likeList = count.data.like.filter(item => {
    //     return item.likerOpenId != wxContext.OPENID
    //   })
    // })
    await likeCollection.where({
      likerOpenId: wxContext.OPENID,
      likedVoiceId: id,
    }).remove()

    await voiceCollection.doc(id).update({
      data: {
        // like: likeList,
        likeCount: _.inc(-1)
      }
    })
  }

  return {
    event,
    openid: wxContext.OPENID
  }
}